/**
 * 网络请求配置
 */
import axios from "axios";

import { message, notification } from 'antd';

axios.defaults.timeout = 100000;
// 文档中的统一设置post请求头
axios.defaults.headers.post['Content-Type'] = 'application/json';
// 如果你是上传文件的话需要设置为
// axios.defaults.headers.post['Content-Type'] = 'multipart/form-data';

// 定义CancelToken相关对象
export const CancelToken = axios.CancelToken;
 /**
  * http request 拦截器
  */
 axios.interceptors.request.use(
   (config) => {
    const token = window.localStorage.getItem('userToken') || window.sessionStorage.getItem('userToken');
    if (token) {
      config.headers = {
        "Authorization": 'Bearer ' + token
      };
    }
    //  if (config.url === '/map/upload' || config.url === '/user/login' || config.url === '/user/update') {
    //   config.headers = {
    //     "Content-Type": 'multipart/form-data',
    //     // "Authorization": 'Bearer ' + token
    //   };
    //  }else{
    //    config.data = JSON.stringify(config.data);
    //    config.headers = {
    //      "Content-Type": "application/json",
    //    };
    //  }
     return config;
   },
   (error) => {
      if (axios.isCancel(error)) {
        console.log('请求已取消');
      } else {
        console.log('请求错误', error);
      }
      return Promise.reject(error);
   }
 );
 
 /**
  * http response 拦截器
  */
 axios.interceptors.response.use(
   (response) => {
    // console.log(response);
    switch (response.data.code) {
      case 200:
        // 成功
        break;
      case 401:
        //未授权
        notification.error({
          message: '',
          description: '您的登录信息已过期,请重新登录',
        });
        localStorage.removeItem('userToken')
        localStorage.removeItem('menu')
        localStorage.removeItem('userInfo')
        localStorage.removeItem('account_status')
        localStorage.removeItem('login_password')
        setTimeout(() => {
          window.location.href = '/'
        }, 2000)
        return
      case 403:
        // 禁止访问
        break;
      case 412:
        // 前端提供信息有误
        break;
      default:
        response.data.message && message.error(response.data.message)
    }
    return response;
   },
   (error) => {
      // message.error('请求失败')
      if (axios.isCancel(error)) {
        console.log('请求已取消');
      } else {
        console.log("请求出错：", error);
      }
      return Promise.reject(error)
   }
 );
 
 /**
  * 封装get方法
  * @param url  请求url
  * @param params  请求参数
  * @param cancelToken  用于取消请求的token
  * @param responseType  返回类型
  * @returns {Promise}
  */
 export function get(url, params = {}, cancelToken, responseType = 'json') {
   return new Promise((resolve, reject) => {
     axios.get(url, {
         params: params,
         responseType, // 默认值
         cancelToken
       }).then((response) => {
          response && resolve(response.data);
       })
       .catch((error) => {
          if (axios.isCancel(error)) {
            console.log('请求已取消');
          } else {
            console.log('请求错误', error);
          }
          reject(error);
       });
   });
 }
 
 /**
  * 封装post请求
  * @param url
  * @param data
  * @param customHeader = {}
  * @param cancelToken  用于取消请求的token
  * @returns {Promise}
  */
 
 export function post(url, data, cancelToken, customHeader = {}) {
   return new Promise((resolve, reject) => {
     axios.post(url, data, {
      headers: customHeader,
      cancelToken
     }).then(
       (response) => {
         //关闭进度条
         response && resolve(response.data);
       },
       (err) => {
          if (axios.isCancel(err)) {
            console.log('请求已取消');
          } else {
            console.log('请求错误', err);
          }
          reject(err);
       }
     );
   });
 }
 
 /**
  * 封装patch请求
  * @param url
  * @param data
  * @param cancelToken  用于取消请求的token
  * @returns {Promise}
  */
 export function patch(url, data = {}, cancelToken) {
   return new Promise((resolve, reject) => {
     axios.patch(url, data, {
      cancelToken
     }).then(
       (response) => {
        resolve(response.data);
       },
       (err) => {
            if (axios.isCancel(err)) {
            console.log('请求已取消');
          } else {
            console.log('请求错误', err);
            msag(err);
          }
          reject(err);
       }
     );
   });
 }
 
 /**
  * 封装put请求
  * @param url
  * @param data
  * @param cancelToken  用于取消请求的token
  * @returns {Promise}
  */
 
 export function put(url, data = {}, cancelToken) {
   return new Promise((resolve, reject) => {
     axios.put(url, data, {cancelToken}).then(
       (response) => {
         response && resolve(response.data);
       },
       (err) => {
          if (axios.isCancel(err)) {
            console.log('请求已取消');
          } else {
            console.log('请求错误', err);
            // msag(err);
          }
          reject(err);
       }
     );
   });
 }
 /**
  * 封装del请求
  * @param url
  * @param data
  * @param cancelToken  用于取消请求的token
  * @returns {Promise}
  */
 
 export function del(url, data = {}, cancelToken) {
   return new Promise((resolve, reject) => {
    axios.delete(url, data, {
      cancelToken
    }).then(
       (response) => {
         resolve(response.data);
       },
       (err) => {
          if (axios.isCancel(err)) {
            console.log('请求已取消');
          } else {
            console.log('请求错误', err);
            //  msag(err);
          }
          reject(err);
       }
     );
   });
 }
 
 //统一接口处理，返回数据
 export default function http(fecth, url, param, cancelToken, responseType = 'json') {
   return new Promise((resolve, reject) => {
     switch (fecth) {
       case "get":
         //console.log("begin a get request,and url:", url);
         get(url, param, cancelToken, responseType)
           .then(function (response) {
             resolve(response);
           })
           .catch(function (error) {
             console.log("get request GET failed.", error);
             reject(error);
           });
         break;
       case "post":
         post(url, param, cancelToken)
           .then(function (response) {
             resolve(response);
           })
           .catch(function (error) {
             console.log("get request POST failed.", error);
             reject(error);
           });
         break;
       default:
         break;
     }
   });
 }
 
 //失败提示
 function msag(err) {
   if (err && err.response) {
     switch (err.response.status) {
       case 400:
         alert(err.response.data.error.details);
         break;
       case 401:
         alert("未授权，请登录");
         break;
 
       case 403:
         alert("拒绝访问");
         break;
 
       case 404:
         alert("请求地址出错");
         break;
 
       case 408:
         alert("请求超时");
         break;
 
       case 500:
         alert("服务器内部错误");
         break;
 
       case 501:
         alert("服务未实现");
         break;
 
       case 502:
         alert("网关错误");
         break;
 
       case 503:
         alert("服务不可用");
         break;
 
       case 504:
         alert("网关超时");
         break;
 
       case 505:
         alert("HTTP版本不受支持");
         break;
       default:
     }
   }
 }
 

 
 